<template>
  <div class="app-page">
    <!-- 操作菜单区 -->
    <my-header>
      <el-button type="primary" @click="handleAddUpdate()" v-repeatClick>添加</el-button>
      <el-button @click="handleBeforeUpdate" v-repeatClick>修改</el-button>
      <el-button @click="view" v-repeatClick>查看</el-button>
      <el-button @click="getPurchase" v-repeatClick>刷新</el-button>
      <el-button type="danger" @click="delPurchase" v-repeatClick>删除</el-button>
    </my-header>

    <!-- 列表区 -->
    <el-card  style="flex: 1;">
      <div class="app-page">
        <div class="content-flex">
          <div>
            <el-form ref="search" :model="search" inline size="small">
              <el-form-item label="" prop="info">
                <el-input
                  placeholder="搜索:采购单号编号/备注"
                  v-model="search.info"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item label="" prop="purchaseLocation">
                <el-select
                  clearable
                  v-model="search.purchaseLocation"
                  placeholder="采购地点"
                  style="width: 100px"
                >
                  <el-option v-for="option in baseFormOptions.purchaseLocation" :key="option" :label="option" :value="option"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="" prop="finished">
                <el-select
                  clearable
                  v-model="search.finished"
                  placeholder="采购是否完成"

                >
                  <el-option label="是" :value="true"></el-option>
                  <el-option label="否" :value="false"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="" prop="dateType">
                <el-select
                  clearable
                  v-model="search.dateType"
                  placeholder="日期类型"
                  style="width: 100px"
                >
                  <el-option label="创建日期" value="创建日期"></el-option>
                  <el-option label="采购日期" value="采购日期"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="" prop="date">
                <el-date-picker
                  v-model="search.date"
                  type="daterange"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="" prop="">
                <el-button type="primary" round @click="searchPage">搜索</el-button>
                <el-button
                  type="warning"
                  round
                  @click="$refs.search.resetFields()"
                >重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <!-- 列表区 -->
        <div style="flex: 1">
          <el-table
            height="100%"
            :data="data"
            border
            stripe
            highlight-current-row
            ref="multipleTable"
            @row-dblclick="handleRowDbclick"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="index" width="55" align="center">
            </el-table-column>
            <el-table-column type="selection" width="55" align="center">
            </el-table-column>
            <el-table-column label="采购单号" prop="orderCode" sortabl width="250">
              <template slot-scope="scope">
                <el-link @click="handleRowDbclick(scope.row)">{{ scope.row.orderCode }}</el-link>
              </template>
            </el-table-column>

            <el-table-column label="采购人员" prop="purchaseUser"  align="center">
            </el-table-column>
            <el-table-column label="商品内容" width="500">
              <template slot-scope="scope">
                <div v-for="item in scope.row.orderGoods" :key="item.id" class="goods-item">
                  <span>{{item.goodsEnglishBrand}}</span>
                  <span>{{item.goodsName}}</span>
                  <span>{{item.specification}}</span>
                  <span>{{item.purchaseNum}} × {{item.purchasePrice}}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="采购地点" prop="purchaseLocation"  align="center">
            </el-table-column>
            <el-table-column label="采购日期" prop="purchaseDate"  align="center" sortable>
            </el-table-column>
            <el-table-column label="采购是否完成" prop="purchaseUser" align="center">
              <template slot-scope="scope">
                <span style="font-size: 20px">
                  <i
                    class="el-icon-circle-check"
                    style="color: #67c23a"
                    v-if="scope.row.finished"
                  ></i>
                  <i
                    class="el-icon-circle-close"
                    style="color: #f56c6c"
                    v-else
                  ></i>
                </span>
              </template>
            </el-table-column>
            <el-table-column
              v-if="!isPurchase"
              label="入库时间"
              sortable
              prop="storageDate"
              align="center"
            ></el-table-column>
            <el-table-column
              label="创建时间"
              sortable
              width="200"
              prop="createTime"
              align="center"
            ></el-table-column>
          </el-table>
        </div>
        <!-- 分页区 -->
        <div style="margin-top: 10px">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[20, 50, 100, 200, 500, 1000]"
            :page-size="pageSize"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </el-card>
    <!-- 添加修改零售预购单信息 -->
    <el-dialog
      v-dialog-drag
      :title="title + (isPurchase?'零售预购单':'零售采购单')"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      width="1250px"
      @close="restForm"
    >
      <el-form
        size="small"
        :model="baseForm"
        label-position="left"
        label-width="100px"
        ref="baseForm"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item prop="orderCode" label="采购单编号">
              <el-input v-model="baseForm.orderCode" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="purchaseUser" label="采购人员">
              <el-input v-model="baseForm.purchaseUser"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购地点" prop="purchaseLocation">
              <el-select
                clearable
                v-model="baseForm.purchaseLocation"
                placeholder="选择采购地点"
                style="width: 100%"
              >
                <el-option v-for="option in baseFormOptions.purchaseLocation" :key="option" :label="option" :value="option"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item prop="purchaseDate" label="采购日期">
              <el-date-picker
                v-model="baseForm.purchaseDate"
                style="width: 100%"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择采购日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="!isPurchase">
            <el-form-item prop="storageDate" label="入库日期">
              <el-date-picker
                v-model="baseForm.storageDate"
                style="width: 100%"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择采购日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="note" label="" label-width="0">
              <el-input v-model="baseForm.note" placeholder="备注"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-table :data="baseForm.orderGoods" border>
          <el-table-column label="操作" align="center" width="80">
            <template slot-scope="scope">
              <el-button
                type="danger"
                circle
                icon="el-icon-close"
                @click="deleteGoods(scope.$index)"
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column label="SKU编码">
            <template slot-scope="scope">
              <el-select v-model="scope.row.goodsSkuCode" clearable filterable @change="handleGoodsChange(scope.row)" allow-create :filter-method="handleGoodsFilter" @focus="baseFormOptions.allGoods = allGoodsClone">
                <el-option v-for="goods in baseFormOptions.allGoods" :key="goods.skuCode" :value="goods.skuCode">
                  <span style="display: inline-block;width:80px">{{goods.skuCode}}</span>
                  <span  style="display: inline-block;width:200px">{{goods.goodsName}}</span>
                  <span  style="display: inline-block;width:80px">{{goods.englishBrand}}</span>
                  <span  style="display: inline-block;width:80px">{{goods.specification}}</span>
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="商品中文名称" prop="goodsName">
          </el-table-column>
          <el-table-column label="英文品牌" prop="goodsEnglishBrand">
          </el-table-column>
          <el-table-column label="规格型号" prop="specification">
          </el-table-column>
          <el-table-column label="计量单位" width="80">
            <template slot-scope="scope">
              <el-select
                filterable
                style="width: 100%"
                v-model="scope.row.measureUnit"
                placeholder="选择计量单位">
                <el-option
                  v-for="item in measuringUnit"
                  :key="item"
                  :value="item"
                  :label="item"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="当下缺货" prop="outOfStoreNum" width="80"></el-table-column>
          <el-table-column label="采购数量" width="120" >
            <template slot-scope="scope">
              <el-input v-model="scope.row.purchaseNum"  controls-position="right" style="width: 100%" :min="0"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="采购单价" >
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.purchasePrice"  controls-position="right" :precision="2" :step="0.1" style="width: 100%" :min="0"></el-input-number>
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align: right; margin-top: 10px">
          <el-link type="primary" :underline="false" @click="addGoods">
            <el-button icon="el-icon-plus" type="primary" circle>
            </el-button>
            添加商品行
          </el-link>
        </div>
        <el-row :gutter="20" style="margin-top:30px">
          <el-col :span="24" style="text-align: right">
            <el-form-item>
              <el-checkbox v-model="baseForm.finished">采购是否完成</el-checkbox>
              <el-button style="margin-left: 10px" @click="restForm">重置</el-button>
              <el-button type="primary" @click="submit" v-if="title!='查看'">保存</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>

let search = {
  //搜索:预购单号编号/备注
  info:'',
  //采购地点
  purchaseLocation:'',
  //采购是否完成
  finished: "",
  //日期类型
  dateType: "",
  //时间范围
  date:[]
};

let goodsForm = {
  //货物英文品牌
  goodsEnglishBrand:'',
  //货物名称
  goodsName:'',
  //货物sku编码
  goodsSkuCode:'',
  //当前缺货数量
  outOfStoreNum:0,
  //采购数量
  purchaseNum:0,
  //采购单价
  purchasePrice:0.00,
  //规格型号
  specification:'',
  //计量单位
  measureUnit:'罐',
}

//零售预购单基本信息表单
let baseForm = {
  id:0,
  //采购是否完成
  finished:false,
  //备注
  note:'',
  //采购单编号
  orderCode:'',
  //采购单货物列表
  orderGoods:[goodsForm],
  //采购日期
  purchaseDate:'',
  //采购地点
  purchaseLocation:'',
  //采购人员
  purchaseUser:'',
  //入库日期
  storageDate:''
};

import myHeader from "@/components/pageHEader/pageHeader";

import { mapGetters } from "vuex";
import {
  getPurchase,
  addPurchase,
  getOrderCode,
  getPurchaseById,
  delPurchase,
  modPurchase,
  getAllGoods
} from "@/api/parts/purchase";

import {
  getStorage,
  addStorage,
  getStorageOrderCode,
  getStorageById,
  delStorage,
  modStorage,
  getStorageAllGoods
} from "@/api/parts/storage";



export default {
  name: "purchase",
  components: {
    myHeader,
  },
  data() {
    return {
      pageSize: 20,
      currentPage: 1,
      total: 0,
      data: [],
      //表格选中
      multipleSelection: [],
      //搜索
      search: this.cloneObj(search),
      //对话框
      dialogFormVisible: false,
      title: "添加",
      baseForm:{},
      baseFormOptions:{
        purchaseLocation:[],
        allGoods:[]
      },
      allGoodsClone:[],
      requestFun:{},
      isPurchase:true
    };
  },
  computed: {
    ...mapGetters(["stores","roles"]),
  },
  created() {
    this.getDic('Place').then(resp=>{
      this.baseFormOptions.purchaseLocation = resp.data.records[0].childrenInfo.map(item=>item.content)
    })
    if(this.$route.path.indexOf('purchase') !=-1){ //零售预购单
      this.isPurchase = true
      delete baseForm.storageDate
      this.requestFun = {
        getReq:getPurchase,
        addReq:addPurchase,
        delReq:delPurchase,
        modReq:modPurchase,
        getOrderCodeReq:getOrderCode,
        getDetailReq:getPurchaseById,
        getAllGoodsReq:getAllGoods
      }
    }else{ //零售采购单
      this.isPurchase = false
      this.requestFun = {
        getReq:getStorage,
        addReq:addStorage,
        delReq:delStorage,
        modReq:modStorage,
        getOrderCodeReq:getStorageOrderCode,
        getDetailReq:getStorageById,
        getAllGoodsReq:getStorageAllGoods
      }
    }
  },
  mounted() {
    this.getPurchase();
    //默认 采购员
    baseForm.purchaseUser = this.roles[0]
    this.baseForm = this.cloneObj(baseForm)
    //获取所有商品
    this.requestFun.getAllGoodsReq().then(resp=>{
      this.baseFormOptions.allGoods = resp.data
      this.allGoodsClone = this.cloneObj(resp.data)
    })
  },
  methods: {
    handleSizeChange(val) {
      this.pageSize = val;
      this.getPurchase()
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getPurchase()
    },
    //重置表单信息
    restForm() {
      this.$nextTick(() => {
        if (this.$refs.baseForm) this.$refs.baseForm.resetFields();
      });
    },
    handleBeforeUpdate(){
      if (!this.multipleSelection.length) {
        this.tip();
        return;
      }
      if (this.multipleSelection.length > 1) {
        this.tip("只能勾选表格中的一条数据");
        return;
      }
      this.handleAddUpdate(this.multipleSelection[0])
    },
    handleAddUpdate(row) {
      //修改处理
      if (row) {
        this.title = "修改";
        this.requestFun.getDetailReq(row.id).then(resp=>{
          let row = resp.data
          //将数据复制给form
          this.handleModform(row, this.baseForm);
          this.baseForm.id = row.id;
          this.dialogFormVisible = true;
        })
      } else {
        if(!localStorage.storeId){
          this.emptyStoreTip()
          return
        }
        this.requestFun.getOrderCodeReq().then(resp=>{ //获取新增时的零售预购单编号
          this.baseForm = this.cloneObj(baseForm);
          this.baseForm.orderCode = resp.msg
          this.title = "添加";
          this.dialogFormVisible = true;
        })
      }
    },
    getPurchase() {
      let query = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        info: this.search.info,
        purchaseLocation:this.search.purchaseLocation,
        finished:this.search.finished,
        dateType:this.search.dateType,
        ...this.handleDate(this.search.date)
      };
      this.requestFun.getReq(query).then((resp) => {
        this.data =  resp.data.records
        this.total = resp.data.total;
      });
    },
    //搜索
    searchPage(){
      this.currentPage = 1
      this.pageSize = 20
      this.getPurchase()
    },
    //表格双击修改
    handleRowDbclick(row) {
      this.handleAddUpdate(row);
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //过滤
    handleGoodsFilter(val){
      if(val){
        this.baseFormOptions.allGoods = this.allGoodsClone.filter(item=> JSON.stringify(item).toLocaleLowerCase().indexOf(((val+'').toLowerCase())) !== -1 )
      }else{
        this.baseFormOptions.allGoods = this.allGoodsClone
      }
    },
    //商品选择切换
    handleGoodsChange(row){
      let goods = this.baseFormOptions.allGoods.filter(item=>item.skuCode == row.goodsSkuCode)[0]
      if(goods){
        row.goodsName = goods.goodsName
        row.goodsEnglishBrand = goods.englishBrand
        row.goodsSkuCode = goods.skuCode
        row.specification = goods.specification
        row.outOfStoreNum = goods.outOfStoreNum
        row.measureUnit = goods.measureUnit
        row.purchasePrice = goods.unitPrice
      }
    },

    //选择仓库名称
    handleStoreChange(val){
      this.stores.forEach(item=>{
        if (val==item.id){
          this.baseForm.storeName = item.name
        }
      })
    },
    //运单收费信息
    addGoods() {
      this.baseForm.orderGoods.push(this.cloneObj(goodsForm));
    },
    deleteGoods(index) {
      if(this.baseForm.orderGoods.length>1){
        this.confirm().then(() => {
          this.baseForm.orderGoods.splice(index, 1);
        });
      }else{
        this.$message.error('删除失败，预购商品至少有一条内容！')
      }
    },
    submit() {
      this.$refs["baseForm"].validate((valid) => {
        if (valid) {
          if(this.baseForm.orderGoods.some(item=>!(item.goodsName && item.goodsEnglishBrand && item.measureUnit && item.specification && item.purchaseNum))){
            this.$message.error('商品品牌，中文名称，规格，单位，数量必填！')
            return;
          }
          let submit = Object.assign(
            this.baseForm
          );
          let request;
          if (this.title == "添加") {
            request = this.requestFun.addReq(submit);
          } else {
            request = this.requestFun.modReq(submit);
          }
          request.then((resp) => {
            this.$message.success(resp.message || "成功");
            this.dialogFormVisible = false;
            this.getPurchase();
          });
        }
      });
    },
    //查看零售预购单信息
    view() {
      this.handleBeforeUpdate();
      this.title = '查看'
    },
    //删除零售预购单信息
    delPurchase() {
      if (!this.multipleSelection.length) {
        this.tip();
        return;
      }
      this.confirm().then(() => {
        this.requestFun.delReq(this.multipleSelection.map((item) => item.id)).then(
          (resp) => {
            this.$message.success(resp.message || "成功");
            this.getPurchase();
          }
        );
      });
    },

  },
};
</script>

<style scoped lang='scss'>
.tdItem {
  line-height: 25px;
}
</style>
